package org.lql.algo.codecrush.week008;

/**
 * @author: liangqinglong
 * @date: 2025-08-19 00:04
 * @description: 706. 设计哈希映射 <a href="https://leetcode.cn/problems/design-hashmap/description/">...</a>
 **/
public class MyHashMap {

	// 链表节点
	private static class Node {
		int key, value;
		Node next;

		Node(int key, int value) {
			this.key = key;
			this.value = value;
		}
	}

	private final int SIZE = 1000; // 桶数量
	private Node[] buckets;

	public MyHashMap() {
		buckets = new Node[SIZE];
	}

	private int hash(int key) {
		return key % SIZE;
	}

	public void put(int key, int value) {
		int idx = hash(key);
		if (buckets[idx] == null) {
			buckets[idx] = new Node(key, value);
			return;
		}
		Node cur = buckets[idx];
		Node prev = null;
		while (cur != null) {
			if (cur.key == key) {
				cur.value = value; // 更新
				return;
			}
			prev = cur;
			cur = cur.next;
		}
		prev.next = new Node(key, value); // 插入新节点
	}

	public int get(int key) {
		int idx = hash(key);
		Node cur = buckets[idx];
		while (cur != null) {
			if (cur.key == key) return cur.value;
			cur = cur.next;
		}
		return -1;
	}

	public void remove(int key) {
		int idx = hash(key);
		Node cur = buckets[idx];
		Node prev = null;
		while (cur != null) {
			if (cur.key == key) {
				if (prev == null) {
					buckets[idx] = cur.next; // 删除头节点
				} else {
					prev.next = cur.next;    // 删除中间节点
				}
				return;
			}
			prev = cur;
			cur = cur.next;
		}
	}

	public static void main(String[] args) {
		MyHashMap myHashMap = new MyHashMap();
		myHashMap.put(1, 1);
		myHashMap.put(2, 2);
		System.out.println(myHashMap.get(1));
		System.out.println(myHashMap.get(3));
		myHashMap.put(2, 1);
		System.out.println(myHashMap.get(2));
		myHashMap.remove(2);
		System.out.println(myHashMap.get(2));
		System.out.println(myHashMap.get(1));
	}
}
